#!/usr/local/bin/python
'''
Created on 2012/06/09

@author: Ryu Naeki
'''

import datetime
import json
import sys
import os
import cgi
import cgitb
cgitb.enable()

from DaoTweet import DaoTweet

class AddLike(object):
    '''
    classdocs
    '''

    def __init__(self):
        '''
        Constructor
        '''
        
    def run(self, like_user, tweet_id):
        dao = DaoTweet(DaoTweet.USERNAME, DaoTweet.PASSWORD, DaoTweet.DBNAME, DaoTweet.CHARSET)
        if dao.like_exists(like_user, tweet_id) == True:
            return
        
        time_now = datetime.datetime.today()        
        dao.add_like(time_now, like_user, tweet_id)
        dao.flush_like_count(tweet_id)
  
if __name__ == "__main__":
    sys.stderr = sys.stdout

    query_string_key = 'QUERY_STRING'
    if query_string_key in os.environ:
        query = cgi.parse_qs(os.environ[query_string_key])
    else:
        query = {}

    key_like_user = 'user'
    if key_like_user in query:
        like_user = cgi.escape(query[key_like_user][0])
    else:
        like_user = None

    key_tweet_id = 'user'
    if key_tweet_id in query:
        tweet_id = cgi.escape(query[key_tweet_id][0])
    else:
        tweet_id = None
    
    if like_user != None and tweet_id != None:
        ad = AddLike()
        # ad.run("gaketest3", 203726068232892416)
        ad.run(like_user, tweet_id)
    
    print "Content-Type: application/json; charset=utf-8"
    print # blank
    if like_user != None and tweet_id != None:
        print json.dumps({"result":"OK"})  
    else:
        print json.dumps({"result":"ERROR"})  
